/************************************************************************
Authors: Kaixin Wang
Project: ETS
Purpose: Plot Histograms of Numbers of Orders.

Date created: 4 March 2022
Version:      STATA 17 MP

Last edited: 11 June 2022
Edited by:   Kaixin	
*************************************************************************/

set more off
clear all
pause on

use "$TRADING_DATA_CLEAN/panel_plant-period-date-bid.dta", clear
drop if bid_status == "REJ"
drop if missing(bid_qty)
sort gpcb_id period date bid_id 

********************************************************************************
*** Distribution of # of bids per plant in a compliance period
********************************************************************************

bysort gpcb_id period: gen num_order = _N
keep gpcb_id commodity num_order
duplicates drop
merge m:1 gpcb_id commodity using "$TRADING_DATA_OUT/inventory_plant-commodity.dta", keepusing(commodity_period)
drop _merge commodity
rename commodity_period period
replace num_order = 0 if missing(num_order)
sort gpcb_id period
order gpcb_id period

forval i=1/10 {
	
	preserve
	
	keep if period == `i'
	
	** compute median number of order
	sum num_order, detail
	local median_order = r(p50)
	
	** truncate at 40
	keep if num_order < 40
	
	if `i' == 6 {
		hist num_order, discrete legend(off) start(-0.5) ///
			width(1) addplot(pci 0 `median_order' 0.5 `median_order') ///
			text(0.4 `median_order'  "Median: `median_order'", size(small) place(se) color(red)) ///
			color(midblue*0.6) lcolor(midblue) ///
			title("Period `i'", size(medium)) ///
			xtitle("Number of bids") ///
			plotregion(color(white)) bgcolor(white) graphregion(color(white)) ///
			name("graph_`i'", replace)	
	}
	else {
		hist num_order, discrete legend(off) start(-0.5) ///
			width(1) addplot(pci 0 `median_order' 0.25 `median_order') ///
			text(0.2 `median_order'  "Median: `median_order'", size(small) place(se) color(red)) ///
			color(midblue*0.6) lcolor(midblue) ///
			title("Period `i'", size(medium)) ///
			xtitle("Number of bids") /// 
			plotregion(color(white)) bgcolor(white) graphregion(color(white)) ///
			name("graph_`i'", replace)
	}
	
	restore
}

graph combine graph_1 graph_2 graph_3 graph_4 graph_5 graph_6 graph_7 graph_8 graph_9 graph_10, ///
	colfirst cols(2) ysize(10) xsize(6) xcommon ///
	graphregion(fcolor(white)) plotregion(fcolor(white))
	
graph export "$TRADING_FIGS/Figure_B2.pdf", replace
